package com.carrental.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.carrental.entity.AdminUser;
import com.carrental.entity.User;
import com.carrental.service.AdminUserService;
import com.carrental.service.UserService;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	UserService userService;
	AdminUserService adminUserService;
       
    /**
     * @throws Exception 
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() throws Exception {
        super();
        userService = new UserService();
        adminUserService = new AdminUserService();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String userType = request.getParameter("userType");
		
		System.out.println("用户登录：" + username + ", " + password + ", " + userType);
		
		try {
			if (userType.equals("a")) {
				AdminUser selectByNamePwd = adminUserService.selectByNamePwd(username, password);
				if (selectByNamePwd != null) {
					request.getSession().setAttribute("user", selectByNamePwd);
					response.sendRedirect("admin.jsp");
				} else {
					response.sendRedirect("login.jsp?error=0");
				}
			} else if (userType.equals("u")) {
				User selectByNamePwd = userService.selectByNamePwd(username, password);
				if (selectByNamePwd != null) {
					request.getSession().setAttribute("user", selectByNamePwd);
					response.sendRedirect("index.jsp");
				} else {
					response.sendRedirect("login.jsp?error=0");
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
